/**
 * 获取画布尺寸
 * @param {string} canvasId - 画布ID
 * @param {Object} component - 组件实例
 * @returns {Promise<Object>} 画布尺寸信息
 */
export function getCanvasSize(canvasId, component) {
  return new Promise((resolve, reject) => {
    if (!canvasId || !component) {
      reject(new Error('canvasId和component参数不能为空'));
      return;
    }
    
    try {
      const query = uni.createSelectorQuery().in(component);
      query.select(`#${canvasId}`)
        .boundingClientRect(data => {
          if (data) {
            resolve({
              width: data.width,
              height: data.height,
              left: data.left,
              top: data.top
            });
          } else {
            reject(new Error('无法获取画布尺寸信息'));
          }
        })
        .exec();
    } catch (error) {
      console.error('[canvasUtils] getCanvasSize error:', error);
      reject(error);
    }
  });
}
 
/**
 * 检查画布是否就绪
 * @param {Object} ctx - 画布上下文
 * @returns {boolean} 是否就绪
 */
export function isCanvasReady(ctx) {
  return ctx && typeof ctx === 'object' && typeof ctx.draw === 'function';
}
 
/**
 * 清空画布指定区域
 * @param {Object} ctx - 画布上下文
 * @param {number} x - 起始x坐标
 * @param {number} y - 起始y坐标
 * @param {number} width - 宽度
 * @param {number} height - 高度
 */
export function clearCanvasArea(ctx, x = 0, y = 0, width, height) {
  if (!isCanvasReady(ctx)) {
    console.warn('[canvasUtils] clearCanvasArea: 画布上下文无效');
    return;
  }
  
  try {
    ctx.clearRect(x, y, width, height);
    ctx.draw();
  } catch (error) {
    console.error('[canvasUtils] clearCanvasArea error:', error);
  }
}
 
/**
 * 设置画布样式
 * @param {Object} ctx - 画布上下文
 * @param {Object} style - 样式配置
 */
export function setCanvasStyle(ctx, style = {}) {
  if (!isCanvasReady(ctx)) {
    console.warn('[canvasUtils] setCanvasStyle: 画布上下文无效');
    return;
  }
  
  try {
    const {
      strokeStyle = '#000000',
      fillStyle = '#000000',
      lineWidth = 2,
      lineCap = 'round',
      lineJoin = 'round',
      globalAlpha = 1
    } = style;
    
    ctx.strokeStyle = strokeStyle;
    ctx.fillStyle = fillStyle;
    ctx.lineWidth = lineWidth;
    ctx.lineCap = lineCap;
    ctx.lineJoin = lineJoin;
    ctx.globalAlpha = globalAlpha;
  } catch (error) {
    console.error('[canvasUtils] setCanvasStyle error:', error);
  }
}
 
/**
 * 坐标转换(屏幕坐标转画布坐标)
 * @param {Object} screenPoint - 屏幕坐标点
 * @param {Object} canvasInfo - 画布信息
 * @returns {Object} 画布坐标点
 */
export function screenToCanvas(screenPoint, canvasInfo) {
  if (!screenPoint || !canvasInfo || 
      typeof screenPoint.x !== 'number' || typeof screenPoint.y !== 'number') {
    return { x: 0, y: 0 };
  }
  
  const { left = 0, top = 0 } = canvasInfo;
  
  return {
    x: screenPoint.x - left,
    y: screenPoint.y - top
  };
}
 
/**
 * 获取系统信息并计算默认画布尺寸
 * @param {number} widthRatio - 宽度比例
 * @param {number} heightRatio - 高度比例
 * @returns {Object} 默认画布尺寸 {width, height}
 */
export function getDefaultCanvasSize(widthRatio = 0.85, heightRatio = 0.95) {
  try {
    const systemInfo = uni.getSystemInfoSync();
    const { windowWidth, windowHeight } = systemInfo;
    
    return {
      width: Math.min(windowWidth * widthRatio, 400),
      height: Math.min(windowHeight * heightRatio, 300)
    };
  } catch (error) {
    console.error('[canvasUtils] getDefaultCanvasSize error:', error);
    return {
      width: 300,
      height: 200
    };
  }
}
 
/**
 * 创建画布上下文
 * @param {string} canvasId - 画布ID
 * @param {Object} component - 组件实例
 * @returns {Object} 画布上下文
 */
export function createCanvasContext(canvasId, component) {
  if (!canvasId) {
    console.error('[canvasUtils] createCanvasContext: canvasId不能为空');
    return null;
  }
  
  try {
    return uni.createCanvasContext(canvasId, component);
  } catch (error) {
    console.error('[canvasUtils] createCanvasContext error:', error);
    return null;
  }
}
 
/**
 * 画布转临时文件
 * @param {string} canvasId - 画布ID
 * @param {Object} options - 转换选项
 * @param {Object} component - 组件实例
 * @returns {Promise} 临时文件路径
 */
export function canvasToTempFile(canvasId, options, component) {
  return new Promise((resolve, reject) => {
    if (!canvasId) {
      reject(new Error('canvasId不能为空'));
      return;
    }
    
    const defaultOptions = {
      fileType: 'png',
      quality: 1,
      destWidth: undefined,
      destHeight: undefined
    };
    
    const finalOptions = { ...defaultOptions, ...options };
    
    try {
      uni.canvasToTempFilePath({
        canvasId,
        ...finalOptions,
        success: (res) => {
          if (res.tempFilePath) {
            resolve(res.tempFilePath);
          } else {
            reject(new Error('生成临时文件失败'));
          }
        },
        fail: (error) => {
          console.error('[canvasUtils] canvasToTempFile error:', error);
          reject(error);
        }
      }, component);
    } catch (error) {
      console.error('[canvasUtils] canvasToTempFile error:', error);
      reject(error);
    }
  });
}
 
/**
 * 检查画布是否为空
 * @param {Object} ctx - 画布上下文
 * @param {number} width - 画布宽度
 * @param {number} height - 画布高度
 * @returns {boolean} 画布是否为空
 */
export function isCanvasEmpty(ctx, width, height) {
  if (!isCanvasReady(ctx) || typeof width !== 'number' || typeof height !== 'number') {
    return true;
  }
  
  try {
    // 获取画布图像数据
    const imageData = ctx.getImageData(0, 0, width, height);
    const data = imageData.data;
    
    // 检查是否所有像素都是透明的
    for (let i = 3; i < data.length; i += 4) {
      if (data[i] !== 0) { // alpha通道不为0表示有内容
        return false;
      }
    }
    
    return true;
  } catch (error) {
    // 如果无法获取图像数据，假设画布不为空
    console.warn('[canvasUtils] isCanvasEmpty: 无法检测画布内容，假设不为空');
    return false;
  }
}
 
/**
 * 默认导出所有画布工具函数
 */
export default {
  getCanvasSize,
  isCanvasReady,
  clearCanvasArea,
  setCanvasStyle,
  screenToCanvas,
  getDefaultCanvasSize,
  createCanvasContext,
  canvasToTempFile,
  isCanvasEmpty
};